# _*_ coding utf-8 _*_
# FILENAME：require.py
# DESCRIPTION: 零件需求管理
# AUTH: jarvis zhang
# DATE: 2022/5/3110:53 上午
import datetime
import threading

import openpyxl
from PyQt5 import QtGui
from PyQt5.QtWidgets import *
from PyQt5.Qt import *
from sqlalchemy import desc
import qtawesome as qta
from components.BaseQueryWindow import BaseQueryWindow, CustomButtonDelegate
from components.MessageBoxComponent import MessageBox
from constant import CalculateType, DownloadType, UploadType
from models.baseModel import get_session, delete
from models.factoryModel import FactoryModel
from models.requireModel import RequireModel, RequireDetailsModel
from utils.logUtils import DownloadLog
from views.log.calculateHandleLogView import CalculateHandleLogWindow
from views.log.downloadHandleLogView import DownloadHandleLogWindow
from views.log.uploadHandleLogView import UploadHandleLogWindow
from views.require.calculateForm import CalculateForm
from views.require.requireDetailList import RequireDetailList
from views.require.uploadDialog import UploadDialog
from views.require.versionDialog import VersionDialog


class RequireList(BaseQueryWindow):
    def __init__(self):
        super(RequireList, self).__init__()
        self.__init_ui()

    ''' UI '''
    def __init_ui(self):
        # 信号槽连接
        self.btn_add.clicked.connect(self.add_click)
        self.btn_close.clicked.connect(self.close)
        self.btn_cal_log.clicked.connect(self.cal_log_click)
        self.btn_log.clicked.connect(self.upload_log_click)
        self.btn_download_log.clicked.connect(self.download_log_click)
        self.btn_refresh.clicked.connect(self.refresh)

    ''' Methods '''
    #  窗体show
    def show(self):
        super(RequireList, self).show()
        self.setWindowTitle("零件需求管理")
        # 设置表头
        self.setTableViewHeaders()
        # 查询
        total = self.query_total(self.edit_vension.text())
        self.setTotalRecordCount(total)  # 总量
        self.recordQuery(0)  # page

        # 关闭窗体,释放资源
    def close(self):
        super(RequireList, self).close()

    def setTableViewHeaders(self):
        self.tableeHeaderLabels = ['编号', '版本名称', '生产线', '所属工厂', '是否运算', '创建时间', '更新时间', '操作']
        self.dataModel.setHorizontalHeaderLabels(self.tableeHeaderLabels)
        # 设置列宽
        self.tableView.setColumnWidth(0, 50)
        self.tableView.setColumnWidth(1, 350)
        self.tableView.setColumnWidth(2, 80)
        self.tableView.setColumnWidth(3, 120)
        self.tableView.setColumnWidth(4, 120)
        self.tableView.setColumnWidth(5, 150)
        self.tableView.setColumnWidth(6, 150)
        self.tableView.setColumnWidth(7, 250)
        #  设置代理按钮,[btnEdit, btnUpload, btnCal, btnView, btnDel, btnDownload]
        delegateBtnIsHiddes = [False, False, False, False, False, False]
        self.tableView.setItemDelegateForColumn(7, CustomButtonDelegate(self, delegateBtnIsHiddes))

    # 刷新
    def refresh(self):
        # 查询
        total = self.query_total(self.edit_vension.text())
        self.setTotalRecordCount(total)  # 总量
        self.recordQuery(0)  # page

    # 记录查询，重写
    def recordQuery(self, limitIndex):
        data = self.page(limitIndex, self.PageRecordCount, self.edit_no.text(), self.edit_vension.text())
        self.dataModel.clear()
        if len(data) > 0:
            for i in range(len(data)):
                # 添加
                newItem = QStandardItem(str(data[i][0].id))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 0, newItem)

                newItem = QStandardItem(str(data[i][0].version_name))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 1, newItem)

                production_line_type = data[i][0].production_line
                production_line = ""
                if production_line_type == 1:
                    production_line = "焊装"
                elif production_line_type == 2:
                    production_line = "涂装"
                else:
                    production_line = "总装"
                newItem = QStandardItem(production_line)
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 2, newItem)

                newItem = QStandardItem(str(data[i][1].name))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 3, newItem)

                status = data[i][0].status
                status_txt = ""
                if status == 2:
                    status_txt = "运算中"
                elif status == 3:
                    status_txt = "运算成功"
                elif status == 4:
                    status_txt = "运算失败"
                else:
                    status_txt = "未运算"
                newItem = QStandardItem(status_txt)
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 4, newItem)

                newItem = QStandardItem(str(data[i][0].create_date))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 5, newItem)

                newItem = QStandardItem(str(data[i][0].update_date))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 6, newItem)

                newItem = QStandardItem("")
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 7, newItem)
        self.setTableViewHeaders()

    # 分页查询列表
    def page(self, limitIndex=0, pageRecordCount=0, no=0, version=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(RequireModel, FactoryModel) \
            .join(FactoryModel, FactoryModel.id == RequireModel.factory_id)
        my_query = my_query.filter(RequireModel.is_del == 0)
        # 拼接查询条件
        if version != "":
            my_query = my_query.filter(RequireModel.version_name.like("%" + version + "%"))
        if no != "":
            my_query = my_query.filter(RequireModel.id == no)
        # 拼接排序条件
        my_query = my_query.order_by(desc(RequireModel.update_date))
        # 分页
        my_query = my_query.offset(limitIndex).limit(pageRecordCount)
        # 执行查询
        model = my_query.all()
        session.close()
        return model

    # 查询数据总量
    def query_total(self, version=None, factory=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(RequireModel, FactoryModel) \
            .join(FactoryModel, FactoryModel.id == RequireModel.factory_id)
        my_query = my_query.filter(RequireModel.is_del == 0)
        # 拼接查询条件
        if version:
            my_query = my_query.filter(RequireModel.version_name == version)
        if factory:
            my_query = my_query.filter(RequireModel.factory_id == factory)
        # 执行查询
        count = my_query.count()
        session.close()
        return count

    # 新增
    def add_click(self):
        VersionDialog.get_dialog(self)

    # 运算日志
    def cal_log_click(self):
        self.cal_log = CalculateHandleLogWindow(type=CalculateType.REQUIRE.value)
        self.cal_log.show()

    # 上传日志
    def upload_log_click(self):
        self.upload_log = UploadHandleLogWindow(type=UploadType.REQUIRE.value)
        self.upload_log.show()

    # 下载日志
    def download_log_click(self):
        self.download_log = DownloadHandleLogWindow(type=DownloadType.REQUIRE.value)
        self.download_log.show()

    # 编辑，继承父类
    def edit_click(self):
        super(RequireList, self).edit_click()
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()
            VersionDialog.get_dialog(self, int(id))

    #  上传，继承父类
    def upload_click(self):
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()
            UploadDialog.get_dialog(self, id)
            print(row)

    #  运算事件
    def cal_click(self):
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = int(self.dataModel.item(row, 0).text())
            factory_name = self.dataModel.item(row, 3).text()
            production_line_name = self.dataModel.item(row, 2).text()
            self.calculateForm = CalculateForm(self, id, factory_name, production_line_name)
            self.calculateForm.show()

    #  查看，继承父类
    def view_click(self):
        print('view')
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()
            title = self.dataModel.item(row, 1).text()
            self.dialog = RequireDetailList(int(id), title)
            self.dialog.show()

    # 删除，继承父类
    def del_click(self):
        choice = QMessageBox.question(self, '', '是否删除当前数据?', QMessageBox.Yes | QMessageBox.No)  # 1
        if choice == QMessageBox.Yes:  # 2
            button = self.sender()
            if button:
                cell = button.index
                row = cell[0]
                id = self.dataModel.item(row, 0).text()
                model = RequireModel()
                model.id = int(id)
                delete(model)
                self.refresh()
        elif choice == QMessageBox.No:  # 4
            pass

    # 下载，继承父类
    def download_click(self):
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()

            '''
            选择路径
            '''
            file_name = "零件需求表"
            fileName, filetype = QFileDialog.getSaveFileName(self,
                                                             "选取目录",
                                                             self.cwd + '/' + file_name,  # 起始路径
                                                             "xlsx(*.xlsx)")  # 设置文件扩展名过滤,用双分号间隔

            if fileName == "":
                return

            '''
            异步下载
            '''
            cal_thread = DownloadThread(id, fileName)
            cal_thread.start()
            messageBox = MessageBox()
            messageBox.warrning("提示", "提交成功，请打开下载日志查看结果！")



"""
异步下载
"""
class DownloadThread(threading.Thread):
    def __init__(self, id, file):
        super(DownloadThread, self).__init__()  # 重构run函数必须写
        self.__id = id
        self.__file = file

    def run(self):
        start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        download_log = DownloadLog(self.__id)
        log_id = download_log.add_log(DownloadType.REQUIRE.value, self.__file, start_time)

        '''
        查询数据
        '''
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(RequireDetailsModel, RequireModel, FactoryModel)
        my_query = my_query.join(RequireModel, RequireModel.id == RequireDetailsModel.require_id)
        my_query = my_query.join(FactoryModel, FactoryModel.id == RequireModel.factory_id)
        my_query = my_query.filter(RequireDetailsModel.is_del == 0)
        my_query = my_query.filter(RequireDetailsModel.require_id == self.__id)
        # 执行查询
        data = my_query.all()
        session.close()

        '''
        导出数据
        '''
        try:
            workbook = openpyxl.Workbook()
            worksheet = workbook.worksheets[0]

            # 写入标题
            worksheet.cell(1, 1, "工厂")
            worksheet.cell(1, 2, "零件名称")
            worksheet.cell(1, 3, "生产线")
            worksheet.cell(1, 4, "零件件号")
            worksheet.cell(1, 5, "到货时间")
            worksheet.cell(1, 6, "数量")
            worksheet.cell(1, 7, "供应商名称")

            if len(data) > 0:
                for i in range(len(data)):
                    if data[i][1].production_line == 1:
                        production_line_name = "焊装"
                    elif data[i][1].production_line == 2:
                        production_line_name = "涂装"
                    else:
                        production_line_name = "总装"

                    worksheet.cell(i + 2, 1, data[i][2].name)
                    worksheet.cell(i + 2, 2, data[i][0].parts_name)
                    worksheet.cell(i + 2, 3, production_line_name)
                    worksheet.cell(i + 2, 4, data[i][0].parts_code)
                    worksheet.cell(i + 2, 5, data[i][0].arrival_time)
                    worksheet.cell(i + 2, 6, data[i][0].quantity)
                    worksheet.cell(i + 2, 7, data[i][0].supplier_name)

            workbook.save(self.__file)
        except Exception as e:
            # 上传失败
            end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            download_log.update_log(log_id, end_time, 2, e)
        else:
            # 上传成功
            end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            download_log.update_log(log_id, end_time, 1)



if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    MainWindow = RequireList()
    MainWindow.show()
    sys.exit(app.exec_())